<template>
  <div class="change-password">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>修改登录密码</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="form.newPwd" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkNewPwd">
          <el-input v-model="form.checkNewPwd" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useEmpStore } from '../store/emp';
import { updatePassword } from '../api';
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const store = useEmpStore()
const { empInfo } = storeToRefs(store)
const formRef = ref<FormInstance>()

const form = reactive({
  newPwd: '',
  checkNewPwd: ''
})

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.newPwd) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度在3-20个字符之间', trigger: 'blur' }
  ],
  checkNewPwd: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
})

const onSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid && empInfo.value) {
      updatePassword(form.newPwd).then(res => {
        console.log("form.newPwd",form.newPwd);
        ElMessage.success('密码修改成功')
        form.newPwd = ''
        form.checkNewPwd = ''
      }).catch(err => {
        ElMessage.error('密码修改失败')
      })
    }
  })
}
</script>

<style scoped>
.change-password {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.box-card {
  width: 480px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

